package com.zbw.printlibrary.printSub;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.util.Log;

import androidx.annotation.NonNull;

import com.printsdk.cmd.PrintCmd;
import com.zbw.printlibrary.bean.AttributeBean;
import com.zbw.printlibrary.printConnector.IPrintCallBack;
import com.zbw.printlibrary.printConnector.PrinterControlCommon;
import com.zbw.printlibrary.util.CheckUtil;
import com.zbw.printlibrary.util.UsbDriver;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 易捷通打印
 */
public class PrintYiJieTong extends PrinterControlCommon {
    private Context mContext;
    private IPrintCallBack mCallBack;
    private UsbManager mUsbManager;
    private UsbDriver mUsbDriver;
    private UsbReceiver mUsbReceiver;
    private final static int PID11 = 8211;
    private final static int PID13 = 8213;
    private final static int PID15 = 8215;
    private final static int VENDORID = 1305;
    private UsbDevice mUsbDev1;        //打印机1
    private UsbDevice mUsbDev2;        //打印机2
    private UsbDevice mUsbDev;
    private static final String ACTION_USB_PERMISSION = "com.usb.sample.USB_PERMISSION";

    public PrintYiJieTong(@NonNull Context mContext, @NonNull IPrintCallBack mCallBack) {
        this.mContext = mContext;
        this.mCallBack = mCallBack;
        getUsbDriverService();
    }

    private void getUsbDriverService() {
        mUsbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
        mUsbDriver = new UsbDriver(mUsbManager, mContext);
        PendingIntent permissionIntent1 = PendingIntent.getBroadcast(mContext, 0,
                new Intent(ACTION_USB_PERMISSION), 0);
        mUsbDriver.setPermissionIntent(permissionIntent1);

        mUsbReceiver = new UsbReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_USB_PERMISSION);
        filter.addAction(mUsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(mUsbManager.ACTION_USB_DEVICE_DETACHED);
        mContext.registerReceiver(mUsbReceiver, filter);
    }

    @Override
    public void connectPrinter() {
        boolean blnRtn = false;
        try {
            if (mUsbDriver.isConnected()) {
                Log.d("tag", "USB线已经连接");
                return;
            }
            for (UsbDevice device : mUsbManager.getDeviceList().values()) {
                if ((device.getProductId() == PID11 && device.getVendorId() == VENDORID)
                        || (device.getProductId() == PID13 && device.getVendorId() == VENDORID)
                        || (device.getProductId() == PID15 && device.getVendorId() == VENDORID)) {
//						if (!mUsbManager.hasPermission(device)) {
//							break;
//						}
                    blnRtn = mUsbDriver.usbAttached(device);
                    if (blnRtn == false) {
                        Log.d("tag", "usbAttached usb设备不可用..");
                        break;
                    }
                    Log.d("tag", "usb设备可以用..");
                    blnRtn = mUsbDriver.openUsbDevice(device);
                    // 打开设备
                    if (blnRtn) {
                        if (device.getProductId() == PID11) {
                            mUsbDev1 = device;
                            mUsbDev = mUsbDev1;
                        } else {
                            mUsbDev2 = device;
                            mUsbDev = mUsbDev2;
                        }
                        Log.d("tag", "连接打印成功");
                        mCallBack.onConnect("连接成功", true);
                        break;
                    } else {
                        mCallBack.onConnect("连接失败", false);
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            mCallBack.onConnect("连接失败", false);
        }
    }

    @Override
    public void disConnectPrinter() {
        try {
            mContext.unregisterReceiver(mUsbReceiver);
            mUsbDriver = null;
            mUsbDev = null;
            mUsbDev1 = null;
            mUsbDev2 = null;
            mCallBack.onDisConnect("断开成功", true);
        } catch (Exception e) {
            e.printStackTrace();
            mCallBack.onDisConnect("断开失败", false);
        }
    }

    @Override
    public void printTest(List<String> testList) {
        if (CheckUtil.isEmpty(testList)) {
            mCallBack.onPrintResult(false);
            return;
        }
        try {
            String title = testList.get(0);
            mUsbDriver.write(PrintCmd.SetAlignment(1));
            mUsbDriver.write(PrintCmd.PrintString(title, 0));

            mUsbDriver.write(PrintCmd.SetAlignment(0));
            for (int i = 1; i < testList.size(); i++) {
                mUsbDriver.write(PrintCmd.PrintString(testList.get(i), 0));
            }
            mUsbDriver.write(PrintCmd.PrintFeedline(8));
            mUsbDriver.write(PrintCmd.PrintCutpaper(1));
            mUsbDriver.write(PrintCmd.SetClean());

            mCallBack.onPrintResult(true);
        } catch (Exception e) {
            e.printStackTrace();
            mCallBack.onPrintResult(false);
        }

    }

    @Override
    public void printString(List<AttributeBean> testList) {
        if (CheckUtil.isEmpty(testList)) {
            mCallBack.onPrintResult(false);
            return;
        }
        try {
            for (int i = 0; i < testList.size(); i++) {
                mUsbDriver.write(PrintCmd.SetAlignment(testList.get(i).getFont_gray()));
                mUsbDriver.write(PrintCmd.PrintString(testList.get(i).getContext(), 0));
            }
            mUsbDriver.write(PrintCmd.PrintFeedline(8));
            mUsbDriver.write(PrintCmd.PrintCutpaper(1));
            mUsbDriver.write(PrintCmd.SetClean());

            mCallBack.onPrintResult(true);
        } catch (Exception e) {
            e.printStackTrace();
            mCallBack.onPrintResult(false);
        }
    }

    @Override
    public void printStringAndBitmap(List<String> testList, LinkedHashMap<Integer,Bitmap> bitmapHashMap) {
        printTest(testList);
    }

    @Override
    public void blueConnect(String address) {

    }

    @Override
    public void disBlueConnect() {

    }

    @Override
    public void openMoneyBox() {

    }

    @Override
    public boolean isConnected() {
        return mUsbDriver.isConnected();
    }

    /*
     *  BroadcastReceiver when insert/remove the device USB plug into/from a USB port
     *  创建一个广播接收器接收USB插拔信息：当插入USB插头插到一个USB端口，或从一个USB端口，移除装置的USB插头
     */
    class UsbReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d("tag", "收到广播.准备连接usb打印.. " + action);
            try {
                if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
                    if (mUsbDriver.usbAttached(intent)) {
                        UsbDevice device = (UsbDevice) intent
                                .getParcelableExtra(UsbManager.EXTRA_DEVICE);
                        if ((device.getProductId() == PID11 && device.getVendorId() == VENDORID)
                                || (device.getProductId() == PID13 && device.getVendorId() == VENDORID)
                                || (device.getProductId() == PID15 && device.getVendorId() == VENDORID)) {
                            if (mUsbDriver.openUsbDevice(device)) {
                                if (device.getProductId() == PID11) {
                                    mUsbDev1 = device;
                                    mUsbDev = mUsbDev1;
                                } else {
                                    mUsbDev2 = device;
                                    mUsbDev = mUsbDev2;
                                }
                            }
                        }
                    }
                } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                    UsbDevice device = (UsbDevice) intent
                            .getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if ((device.getProductId() == PID11 && device.getVendorId() == VENDORID)
                            || (device.getProductId() == PID13 && device.getVendorId() == VENDORID)
                            || (device.getProductId() == PID15 && device.getVendorId() == VENDORID)) {
                        mUsbDriver.closeUsbDevice(device);
                        if (device.getProductId() == PID11)
                            mUsbDev1 = null;
                        else
                            mUsbDev2 = null;
                    }
                } else if (ACTION_USB_PERMISSION.equals(action)) {
                    synchronized (this) {
                        UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                        if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                            if ((device.getProductId() == PID11 && device.getVendorId() == VENDORID)
                                    || (device.getProductId() == PID13 && device.getVendorId() == VENDORID)
                                    || (device.getProductId() == PID15 && device.getVendorId() == VENDORID)) {
                                if (mUsbDriver.openUsbDevice(device)) {
                                    if (device.getProductId() == PID11) {
                                        mUsbDev1 = device;
                                        mUsbDev = mUsbDev1;
                                    } else {
                                        mUsbDev2 = device;
                                        mUsbDev = mUsbDev2;
                                    }
                                }
                            }
                        } else {
                            Log.d("tag", "permission denied for device");
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void printString(List<AttributeBean> testList, int width) {

    }

}
